﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UNSWThink
{
   /// <summary>
   /// Windows form that is used to reorder the questions ordering
   /// </summary>
   public partial class ReorderQuestionsForm : Form
   {
      private DBConnection dbConnection;
      private DataTable questions;
      private DataTable relatedQuestions;
      private int rowIndex;

      /// <summary>
      /// Default constructor
      /// </summary>
      /// <param name="dbConnection">
      /// Object used for accessing the database
      /// </param>
      /// <param name="questions">
      /// Data table of all retrieved questions
      /// </param>
      /// <param name="relatedQuestions">
      /// Data table of all class related questions
      /// </param>
      public ReorderQuestionsForm(DBConnection dbConnection, DataTable questions, DataTable relatedQuestions)
      {
         InitializeComponent();

         this.dbConnection = dbConnection;
         this.questions = questions;
         this.relatedQuestions = relatedQuestions.Copy();
      }

      #region WINDOWS FORM EVENTS

      private void ReorderQuestionsForm_Load(object sender, EventArgs e)
      {
         // check responses contain expected table column name precondition
         if (HelperMethods.CheckColumnsExists(questions, Defs.QUESTION_COLUMN_NAMES) &&
             HelperMethods.CheckColumnsExists(relatedQuestions, Defs.QUESTION_COLUMN_NAMES))
         {
            // initalise various properties of the questions data grid view control
            dataGridViewQuestions.DataSource = relatedQuestions;
            dataGridViewQuestions.Sort(dataGridViewQuestions.Columns["number"], ListSortDirection.Ascending);

            dataGridViewQuestions.Columns["id"].Visible = false;
            dataGridViewQuestions.Columns["class"].Visible = false;
            dataGridViewQuestions.Columns["image"].Visible = false;
            dataGridViewQuestions.Columns["number"].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
            dataGridViewQuestions.Columns["description"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridViewQuestions.Columns["type"].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
         }
      }

      #endregion

      #region CONTROL EVENTS

      private void buttonCancel_Click(object sender, EventArgs e)
      {
         this.Close();
      }

      private void dataGridViewQuestions_SelectionChanged(object sender, EventArgs e)
      {
         if (dataGridViewQuestions.SelectedRows.Count > 0)
         {
            rowIndex = dataGridViewQuestions.SelectedRows[0].Index;
         }
      }

      /// <summary>
      /// Button event used to control moving a question up the list and updating all necessary data
      /// </summary>
      /// <param name="sender">object sender</param>
      /// <param name="e">EventArgs e</param>
      private void buttonUp_Click(object sender, EventArgs e)
      {
         if (dataGridViewQuestions.SelectedRows.Count > 0)
         {
            // check that the row index is within row collection range to 
            // avoid index out of range exception
            rowIndex = dataGridViewQuestions.SelectedRows[0].Index;
            if ((rowIndex >= 0) && (rowIndex < relatedQuestions.Rows.Count))
            {
               int questionID = (int)dataGridViewQuestions.Rows[rowIndex].Cells["id"].Value;
               int questionRowIndex = HelperMethods.GetIndexOfTableID(relatedQuestions, questionID);
               int questionNumber = (int)relatedQuestions.Rows[questionRowIndex]["number"];

               // check that the question number is within question number range of valid question numbers
               if ((questionNumber > 1) && (questionNumber <= relatedQuestions.Rows.Count))
               {
                  for (int i = 0; i < relatedQuestions.Rows.Count; i++)
                  {
                     // update rows that are not the currently selected row
                     if (i != questionRowIndex)
                     {
                        // update the row that is the previous question of the currently selected question
                        int tempQuestionNumber = (int)relatedQuestions.Rows[i]["number"];
                        if (tempQuestionNumber == questionNumber - 1)
                        {
                           relatedQuestions.Rows[i]["number"] = tempQuestionNumber + 1;
                        }

                     }
                  }

                  // update the currently selected question
                  if (questionNumber > 0)
                  {
                     relatedQuestions.Rows[questionRowIndex]["number"] = questionNumber - 1;
                     dataGridViewQuestions.DataSource = relatedQuestions;
                     dataGridViewQuestions.Sort(dataGridViewQuestions.Columns["number"], ListSortDirection.Ascending);
                  }
               }
            }
         }
      }

      /// <summary>
      /// Button event used to control moving a question down the list and updating all necessary data
      /// </summary>
      /// <param name="sender">object sender</param>
      /// <param name="e">EventArgs e</param>
      private void buttonDown_Click(object sender, EventArgs e)
      {
         if (dataGridViewQuestions.SelectedRows.Count > 0)
         {
            // check that the row index is within row collection range to 
            // avoid index out of range exception
            rowIndex = dataGridViewQuestions.SelectedRows[0].Index;
            if ((rowIndex >= 0) && (rowIndex < relatedQuestions.Rows.Count))
            {
               int questionID = (int)dataGridViewQuestions.Rows[rowIndex].Cells["id"].Value;
               int questionRowIndex = HelperMethods.GetIndexOfTableID(relatedQuestions, questionID);
               int questionNumber = (int)relatedQuestions.Rows[questionRowIndex]["number"];

               // check that the question number is within question number range of valid question numbers
               if ((questionNumber >= 1) && (questionNumber < relatedQuestions.Rows.Count))
               {
                  for (int i = 0; i < relatedQuestions.Rows.Count; i++)
                  {
                     // update rows that are not the currently selected row
                     if (i != questionRowIndex)
                     {
                        // update the row that is the previous question of the currently selected question
                        int tempQuestionNumber = (int)relatedQuestions.Rows[i]["number"];
                        if (tempQuestionNumber == questionNumber + 1)
                        {
                           relatedQuestions.Rows[i]["number"] = tempQuestionNumber - 1;
                        }

                     }
                  }

                  // update the currently selected question
                  if (questionNumber > 0)
                  {
                     relatedQuestions.Rows[questionRowIndex]["number"] = questionNumber + 1;
                     dataGridViewQuestions.DataSource = relatedQuestions;
                     dataGridViewQuestions.Sort(dataGridViewQuestions.Columns["number"], ListSortDirection.Ascending);
                  }
               }
            }
         }
      }

      /// <summary>
      /// Button event that commits all of the changes to the database and program's memory
      /// </summary>
      /// <param name="sender">object sender</param>
      /// <param name="e">EventArgs e</param>
      private void buttonOK_Click(object sender, EventArgs e)
      {
         for (int i = 0; i < relatedQuestions.Rows.Count; i++)
         {
            string columnName = "number";
            int id = (int)relatedQuestions.Rows[i]["id"];
            int questionNumber = (int)relatedQuestions.Rows[i]["number"];

            // update database
            bool updated = dbConnection.UpdateRecord("Question", columnName, id, questionNumber);
            // if database update was successful, update the program's memory
            if (updated)
            {
               int rowIndex = HelperMethods.GetIndexOfTableID(questions, id);
               HelperMethods.UpdateTable(questions, rowIndex, 
                  new string[1] { columnName }, new object[1] { questionNumber });
            }
         }
         this.Close();
      }

      #endregion
   }
}
